package com.gopay.common.cps.dao.wallet.base.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.gopay.common.base.dao.impl.BaseDAOImpl;
import com.gopay.common.constants.cust.CustCaCertConstants;
import com.gopay.common.cps.dao.wallet.base.WaCertificateDao;
import com.gopay.common.domain.dps.WaCertificate;
import com.gopay.common.order.dao.CommonQueryDAO;
import com.gopay.common.util.DateUtils;
import com.gopay.common.util.FastJsonUtil;

@Service("waCertificateDao")
public class WaCertificateDaoImpl extends BaseDAOImpl<WaCertificate, Serializable> implements WaCertificateDao {

	@Resource(name = "commonQueryDAO")
    private CommonQueryDAO commonQueryDAO;
	
	protected Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 插入发送的消息内容
	 * @param send
	 */
	@Override
	public WaCertificate saveWaCertificate(WaCertificate waCertificate){
		WaCertificate wc = null;
		try {
			wc = super.save(waCertificate);
		} catch (Exception e) {
			logger.error("saveWaCertificate异常",e);
		}
		return wc;
	}
	 /**
	  * 更新数据的状态
	  */
	 @Override
	public void updateAwMsgSend(WaCertificate waCertificate){
		 super.update(waCertificate);
	 }
	 
	@Override
    public WaCertificate queryByDeviceIdAndUserId(String deviceId , String userId){
		String hql = " select m from WaCertificate m where m.userId = :userId and m.deviceId = :deviceId";
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userId", userId);
        params.put("deviceId", deviceId);
		List<WaCertificate> waCertificateList = findByHql(hql ,params);
		if(waCertificateList!=null && waCertificateList.size()==1){
			return waCertificateList.get(0);
		}
		return null;
		
	}
	
	@Override
    public List<WaCertificate> queryByCustId(String custId ){
		String hql = " select m from WaCertificate m where m.custId = :custId";
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("custId", custId);
		List<WaCertificate> waCertificateList = findByHql(hql ,params);
		return waCertificateList;
		
	}
	
	@Override
	public int deleteByCustId(String custId){
		String hql = " delete  from  Wa_Certificate m where m.cust_Id = :custId";
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("custId", custId);
		return super.updateBySql(hql,params);
	}
	
	@Override
	public WaCertificate queryBySn(String sn) {
		String hql = " select m from WaCertificate m where m.sn = :sn ";
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sn", sn);
		List<WaCertificate> waCertificateList = findByHql(hql ,params);
		if(waCertificateList!=null && waCertificateList.size()==1){
			return waCertificateList.get(0);
		}
		return null;
	}
	 
	@Override
	public List<WaCertificate> getCustCaCertListByUserId(String userId, String stat) {
		String hql = "from WaCertificate where stat= :stat and "
				+ " userId = :userId ";
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("stat", stat);
		param.put("userId", userId);
		
		List<WaCertificate> list = findByHql(hql, param);
		return list;
	}
	 
	@Override
	public List<WaCertificate> getCustCertList(String userId, String deviceId, String stat) {
		String hql = "from WaCertificate where certInstallStat= :stat and "
				+ " userId = :userId and deviceId = :deviceId ";
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("stat", stat);
		param.put("userId", userId);
		param.put("deviceId", deviceId);
		
		List<WaCertificate> list = findByHql(hql, param);
		
		return list;
	}
	
	@Override
	public List<WaCertificate> getLimitWaCertificate() {
		/**
		 * 查询出状态为启用，并且已经过期的数据
		 */
		String hql = "from WaCertificate where stat= :stat and "
				   + "TO_CHAR(VALID_TO,'yyyy-MM-dd') <= :currentDate ";
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("stat", CustCaCertConstants.CUST_CA_CERT_STAT_ACTIVE);
		param.put("currentDate", DateUtils.format(new Date(), "yyyy-MM-dd"));
		
		List<WaCertificate> list = findByHql(hql, param);
		return list;
	}
	 
	@Override
	public void updateCertApplyStatus(long buyDtlId) {
		Map<String,Object> param = new HashMap<String,Object>(16);
		StringBuffer sql = new StringBuffer();
		sql.append("update wa_certificate ca ")
		.append("set ca.cert_install_stat = '02' ")
		.append("where ca.cert_install_stat = '03'  ")
		.append("and ca.id in (select r.cert_id  ")
		.append("from wa_certificate_allocation r  ")
		.append("where r.cert_buy_id =:buyDtlId ")
		.append("and r.allocation_status = '02') ");
		
		param.put("buyDtlId", buyDtlId);
		
		logger.info("更新企业版移动数字证书申请记录SQL:{},[参数]：{}",sql.toString(), FastJsonUtil.toJSONString(param));
		
		this.updateBySql(sql.toString(), param);
	}
	
	@Override
	public void batchInsertApplyCert(long buyDtlId) {
		//给财务员分配证书，财务员安装失败，没有继续安装，证书安装时间过期，证书被回收，则往安装记录表中插入申请数据
		Map<String,Object> param = new HashMap<String,Object>(16);
		StringBuffer sql = new StringBuffer();
		
		sql.append("select r.cert_id, c.cust_id, c.cust_type, c.cert_name,c.device_id,c.phone_model,c.user_id ")
		.append("from wa_certificate_allocation r ")
		.append("left join wa_certificate c on r.cert_id = c.id  ")
		.append("where r.cert_buy_id =:buyDtlId  ")
		.append("and c.cert_install_stat = '00'  ")
		.append("and nvl(r.is_update,'xx')<>'1'  ");
		
		param.put("buyDtlId", buyDtlId);
		logger.info("查询安装失败的证书记录SQL:{},[参数]：{}",sql.toString(), FastJsonUtil.toJSONString(param));
		List<Object[]> list = commonQueryDAO.findBySql(sql.toString(), param);
		if (null == list || list.size() ==0 ) {
			logger.info("没有安装失败的待回收的数字证书");
			return;
		}
		List<WaCertificate> certList = new ArrayList<WaCertificate>();
		for (Object[] bean : list) {
			WaCertificate cert = new WaCertificate();
			cert.setCustId(bean[1].toString());
			cert.setCustType(bean[2].toString());
			cert.setCertName(bean[3].toString());
			cert.setCertUrl("/");
			cert.setStat("01");
			cert.setCertInstallStat("02");
			cert.setDeviceId(bean[4].toString());
			cert.setPhoneModel(bean[5].toString());
			cert.setUserId(bean[6].toString());
			cert.setCreateTime(new Date());
			cert.setLastUptTs(new Date());
			certList.add(cert);
		}
		
		if (certList.size() > 0) {
			logger.info("批量插入证书申请记录记录:{}", FastJsonUtil.toJSONString(certList));
			this.saveOrUpdateAll(certList);
		}
	}
	@Override
	public WaCertificate getCertByUserIdAndDeviceId(String userId, String deviceId) {
		String hql = " select m from WaCertificate m where m.userId = :userId and m.deviceId = :deviceId order by createTime desc";
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userId", userId);
        params.put("deviceId", deviceId);
		List<WaCertificate> waCertificateList = findByHql(hql ,params);
		if(waCertificateList!=null && waCertificateList.size()>0){
			return waCertificateList.get(0);
		}
		return null;
	}
}
